<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MarriageHistory extends Model
{
    protected $table = 'st_medical_marriagehistory';

    protected $fillable = [
        'record_id',
        'marriage',
        'macrosomia',
        'menstruation',
        'menopause',
        'remark',
    ];

    //  修改器
    public function setMacrosomiaAttribute($value)
    {
        if (is_null($value))
            $this->attributes['macrosomia'] = $value;
        $this->attributes['macrosomia'] = $value ? 1 : 0;
    }

    public function setMarriageAttribute($value)
    {
        $this->attributes['marriage'] = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }

    public function setMenstruationAttribute($value)
    {
        $this->attributes['menstruation'] = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }

    public function setMenopauseAttribute($value)
    {
        $this->attributes['menopause'] = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }

    //  获取器
    public function getMacrosomiaAttribute($value)
    {
        if ($value) {
            return ['key' => $value, 'value' => app('field')->get('marriage')['macrosomia'][$value]];
        }
    }

    public function getMarriageAttribute($value)
    {
        return $value ? json_decode($value, true) : '';
    }

    public function getMenstruationAttribute($value)
    {
        $value = $value ? json_decode($value, true) : '';

        if (is_array($value)) {

            $marriage = app('field')->get('marriage');

            if (isset($value['cycle']['law']) && $value['cycle']['law'] != '') {
                $value['cycle']['law'] = [
                    'key' => $value['cycle']['law'],
                    'value' => $marriage['menstruation']['law'][$value['cycle']['law']],
                ];
            }

            if (isset($value['period']['law']) &&  $value['period']['law'] != '') {
                $value['period']['law'] = [
                    'key' => $value['period']['law'],
                    'value' => $marriage['menstruation']['law'][$value['period']['law']],
                ];
            }
        }

        return $value;
    }

    public function getMenopauseAttribute($value)
    {
        return $value ? json_decode($value, true) : '';
    }
}
